package com.marco.gisdata.runnable;

import com.google.common.collect.Maps;
import com.marco.commons.RedisKey;
import com.marco.gisdata.service.impl.BaiduGisServiceImpl;
import com.marco.ipdata.service.ChinaIPService;
import com.marco.ipdata.service.impl.BaiduApiServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Map;

/**
 * BaiduGisApiRunnable.java
 * Create on 2017/3/23
 * Copyright(c) JD Inc 2017. All Rights Reserved.
 * <pre>
 * 功能说明：百度接口根据TOKEN开启线程，进行遍历数据
 * </pre>
 */
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BaiduGisApiRunnable implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(BaiduGisApiRunnable.class);
    //该线程使用的ak
    private String ak;
    //线程名称
    private String threadName;
    @Autowired
    private BaiduGisServiceImpl baiduGisService;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public void run() {
        this.setThreadName(threadName);
        logger.info("开启线程处理 百度GIS 数据，请稍候---------------");
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String line = null;
            while (StringUtils.isNotBlank(line = jedis.rpop(RedisKey.GIS_DATA_LIST))) {
                String[] params = line.split("\\|");
                Map<String, String> param = Maps.newHashMap();
                param.put("ak", ak);
                param.put("location", params[0] + "," + params[1]);
                param.put("coordtype","wgs84ll");
                param.put("output","json");
                //TODO 百度接口的相关参数
                baiduGisService.invokeGet(param, line);
            }
        } catch (Exception e) {
            logger.error("开启线程调用百度GIS数据出现异常", e);
        } finally {
            IOUtils.closeQuietly(jedis);
        }
    }

    public void setAk(String ak) {
        this.ak = ak;
    }

    public void setThreadName(String threadName) {
        this.threadName = threadName;
    }
}
